"""
统一配置管理模块
整合DailyHotApi和FastAPI平台配置
"""

from typing import List, Union, Optional, Dict, Any
from pydantic_settings import SettingsConfigDict
from pydantic import validator, Field
import sys
from pathlib import Path

# 添加backend目录到Python路径
sys.path.insert(0, str(Path(__file__).parent.parent))

# 从统一配置模块导入
try:
    from settings import settings as global_settings
except ImportError:
    print("Warning: Failed to import global settings. Using fallback configuration.")
    from pydantic_settings import BaseSettings
    import json
    import os
    
    class Settings(BaseSettings):
        PROJECT_NAME: str = "FastAPI Platform"
        VERSION: str = "1.0.0"
        DESCRIPTION: str = "python工具平台"
        ENVIRONMENT: str = "development"
        DEBUG: bool = True
        
        HOST: str = "localhost"
        PORT: int = 8989
        RELOAD: bool = False
        RELOAD_DIRS: List[str] = ["app"]
        
        DATABASE_URL: str = "postgresql://postgres:123456@localhost:5432/toolplatform?client_encoding=utf8"
        DATABASE_POOL_SIZE: int = 10
        DATABASE_MAX_OVERFLOW: int = 20
        DATABASE_POOL_RECYCLE: int = 3600
        DATABASE_POOL_TIMEOUT: int = 30
        DATABASE_CONNECT_TIMEOUT: int = 10
        
        SECRET_KEY: str = "fastapi-platform-2025-super-secret-key"
        ALGORITHM: str = "HS256"
        ACCESS_TOKEN_EXPIRE_MINUTES: int = 30
        REFRESH_TOKEN_EXPIRE_DAYS: int = 7
        
        BACKEND_CORS_ORIGINS: List[str] = ["http://localhost:3000", "http://localhost:5173", "http://localhost:8989"]
        
        @validator("BACKEND_CORS_ORIGINS", pre=True)
        def assemble_cors_origins(cls, v: Union[str, List[str]]) -> List[str]:
            if isinstance(v, str):
                if v.strip().startswith("["):
                    try:
                        return json.loads(v)
                    except (json.JSONDecodeError, ValueError):
                        v = v.strip("[]")
                        return [i.strip().strip('"\'') for i in v.split(",") if i.strip()]
                else:
                    return [i.strip() for i in v.split(",") if i.strip()]
            elif isinstance(v, list):
                return v
            return []
        
        REDIS_URL: str = "redis://localhost:6379"
        
        # Celery配置
        CELERY_BROKER_URL: str = "redis://localhost:6379/1"
        CELERY_RESULT_BACKEND: str = "redis://localhost:6379/2"
        
        UPLOAD_DIR: str = "uploads"
        MAX_FILE_SIZE: int = 10 * 1024 * 1024
        ALLOWED_FILE_TYPES: List[str] = ["jpg", "jpeg", "png", "gif", "pdf", "txt", "md"]
        
        @validator("ALLOWED_FILE_TYPES", pre=True)
        def assemble_allowed_file_types(cls, v: Union[str, List[str]]) -> List[str]:
            if isinstance(v, str):
                if v.strip().startswith("["):
                    try:
                        return json.loads(v)
                    except (json.JSONDecodeError, ValueError):
                        v = v.strip("[]")
                        return [i.strip().strip('"\'') for i in v.split(",") if i.strip()]
                else:
                    return [i.strip() for i in v.split(",") if i.strip()]
            elif isinstance(v, list):
                return v
            return []
        
        model_config = SettingsConfigDict(
            env_file=".env",
            env_file_encoding="utf-8",
            case_sensitive=True,
            extra="ignore",
        )
    
    global_settings = Settings()


class Settings:
    """配置兼容层
    保持与原有代码的兼容性，所有属性都转发到全局配置
    """
    def __init__(self):
        # 复制全局配置的所有属性
        self._global_settings = global_settings
        
    def __getattr__(self, name):
        # 首先尝试从全局配置的顶层属性获取
        if hasattr(self._global_settings, name):
            return getattr(self._global_settings, name)
        
        # 然后尝试从全局配置的子模块获取
        for submodule in [
            'database', 'security', 'server', 'cors', 'redis', 
            'file_upload', 'email', 'logging', 'pagination', 
            'hot_api', 'llm'
        ]:
            if hasattr(self._global_settings, submodule):
                sub_config = getattr(self._global_settings, submodule)
                if hasattr(sub_config, name):
                    return getattr(sub_config, name)
        
        # 对于LLM相关配置的特殊处理
        if name.startswith('LLM_'):
            llm_name = name[4:]
            if hasattr(self._global_settings.llm, llm_name):
                return getattr(self._global_settings.llm, llm_name)
        
        # 如果找不到属性，返回None
        return None

    @property
    def is_production(self) -> bool:
        """是否为生产环境"""
        return self._global_settings.ENVIRONMENT == "production"

    @property
    def is_development(self) -> bool:
        """是否为开发环境"""
        return self._global_settings.ENVIRONMENT == "development"

    @property
    def is_testing(self) -> bool:
        """是否为测试环境"""
        return self._global_settings.ENVIRONMENT == "testing"

    @property
    def log_config(self) -> Dict[str, Any]:
        """获取日志配置字典"""
        return {
            "log_level": self._global_settings.logging.LOG_LEVEL,
            "log_file": self._global_settings.logging.LOG_FILE,
            "enable_console": self._global_settings.logging.LOG_ENABLE_CONSOLE,
            "enable_file": self._global_settings.logging.LOG_ENABLE_FILE,
            "debug_mode": self._global_settings.DEBUG
        }

    # API配置
    @property
    def API_V1_STR(self) -> str:
        return "/api/v1"
    
    @property
    def DOCS_URL(self) -> str:
        return "/docs"
    
    @property
    def REDOC_URL(self) -> str:
        return "/redoc"
    
    @property
    def OPENAPI_URL(self) -> str:
        return "/openapi.json"


# 全局配置实例
settings = Settings()

# 热点平台配置
PLATFORM_CONFIG = {
    "zhihu": {
        "name": "知乎",
        "type": "热榜",
        "description": "知乎实时热榜",
        "base_url": "https://www.zhihu.com",
        "api_url": "https://api.zhihu.com/topstory/hot-lists/total",
        "headers": {
            "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36"
        }
    },
    "bilibili": {
        "name": "哔哩哔哩",
        "type": "排行榜",
        "description": "B站全站排行榜",
        "base_url": "https://www.bilibili.com",
        "api_url": "https://api.bilibili.com/x/web-interface/ranking/v2",
        "headers": {
            "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36",
            "Referer": "https://www.bilibili.com"
        },
        "params": {
            "0": "全站",
            "1": "动画",
            "3": "音乐",
            "4": "游戏",
            "5": "娱乐",
            "119": "鬼畜",
            "129": "舞蹈",
            "155": "时尚",
            "160": "生活",
            "188": "科技"
        }
    },
    "weibo": {
        "name": "微博",
        "type": "热搜",
        "description": "微博实时热搜榜",
        "base_url": "https://s.weibo.com",
        "api_url": "https://weibo.com/ajax/side/hotSearch",
        "headers": {
            "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36"
        }
    }
    # 其他53个平台配置将在后续任务中添加
}


def get_platform_config(platform: str) -> dict:
    """获取平台配置"""
    return PLATFORM_CONFIG.get(platform, {})


def get_all_platforms() -> List[str]:
    """获取所有支持的平台列表"""
    return list(PLATFORM_CONFIG.keys())